package com.example.cyberqueueandroid;

import java.util.Timer;
import java.util.TimerTask;

import com.tauproject.EZQueue.R;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Parcelable;


public class NotifierService extends Service {
	private static boolean isRunning = false;

	private Timer mTimer = null;
	private int mNotificationID = 145;
	private NotificationManager mNotificationManager;
	private Intent mStartIntent = null;
	private boolean mIsNotified = false;

	@Override
	public void onCreate() {
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// showNotification(-1);
	}

	@Override
	public void onDestroy() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
			isRunning = false;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mStartIntent = intent;
		run();
		return Service.START_STICKY;
	}

	private void run() {
		if (isRunning == true) {
			return;
		}
		isRunning = true;
		mTimer = new Timer();
		mTimer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				notiferUpdater();
			}
		}, 0, 5000);
	}

	private void notiferUpdater() {
		int pos = SharedData.POS_MANAGER.getUserPosition();
		if (pos >= 0) {
			showNotification(pos);
			audioNotification(pos);
		} else {
			// mTimer.cancel();
		}
	}

	private void audioNotification(int pos) {
		if (pos == 0 && mIsNotified == false) {
			mIsNotified = true;
			try {
				Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
				Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
				r.play();
			} catch (Exception e) {
			}
		}
		if (pos != 0) {
			mIsNotified = false;
		}
	}

	private void showYourTurnAlert() {
		Intent dialogIntent = new Intent(getBaseContext(), YourTurnAlertActivity.class);
		dialogIntent.setAction("showAlert");
		dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		getApplication().startActivity(dialogIntent);
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	private void showNotification(int position) {
		CharSequence text = getText(R.string.service_started);
		Notification notification = new Notification(R.drawable.ezqeue, text, System.currentTimeMillis());
		Intent onPressIntent = null;
		if (position == 0) {
			onPressIntent = new Intent(this, MainActivity.class);
			onPressIntent.setData(Uri.parse(SharedData.URI + "/user_page?queue_id="
					+ SharedData.POS_MANAGER.getQueueID()));
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, onPressIntent, 0);
			notification.setLatestEventInfo(this, "your turn is now", text, contentIntent);
		} else if (position == -1) {
			onPressIntent = new Intent(this, MainActivity.class);
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
			notification.setLatestEventInfo(this, "retrieving status...", text, contentIntent);
		} else if (position == -2) {
			onPressIntent = new Intent(this, MainActivity.class);
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, onPressIntent, 0);
			notification.setLatestEventInfo(this, "you are not in a queue", text, contentIntent);
		} else {
			onPressIntent = new Intent(this, MainActivity.class);
			onPressIntent.setAction(Intent.ACTION_VIEW);
			onPressIntent.setData(Uri.parse(SharedData.URI + "/user_page?queue_id="
					+ SharedData.POS_MANAGER.getQueueID()));
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, onPressIntent, 0);
			notification.setLatestEventInfo(this, "your position: " + position, text, contentIntent);
		}
		if (mStartIntent != null) {
			Intent dismissIntent = new Intent(this, DismissNotificationReceiver.class);
			dismissIntent.putExtra("startupIntent", (Parcelable) mStartIntent);
			dismissIntent.setAction("notification_cancelled");
			notification.deleteIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, dismissIntent,
					PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
		}
		mNotificationManager.notify(mNotificationID + hashString("test"), notification);
	}

	private int hashString(String s) {
		if (s == null || s.length() == 0) {
			return 0;
		}
		int hash = 7;
		for (int i = 0; i < s.length(); i++) {
			hash = hash * 31 + s.charAt(i);
		}
		return hash;
	}
}
